<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Home\Controller;
use Think\Controller;

/**
 * 前台公共控制器
 * 为防止多分组Controller名称冲突，公共Controller名称统一使用分组名称
 */
class HomeController extends Controller {

	/* 空操作，用于输出404页面 */
	public function _empty(){
		$this->error('404');
	}

    protected function _initialize(){
        /* 读取站点配置 */
        $config = api('Config/lists');
        C($config); //添加配置
        $token = I('token');
        if (!empty($token)) {
            $uid = M('member_token')->where(array('token'=>$token))->getField('uid');
            D('Member')->login($uid);
        }
        if (is_login()) {
            define('UID',is_login());
        }
        if(!C('WEB_SITE_CLOSE')){
            $this->error('站点已经关闭，请稍后访问~');
        }
        if (is_wechat()) {
            $this->assign("is_wechat",1);
            vendor("wechat/jssdk");
            // $jssdk = new \JSSDK("wx839cb838ca028e3e", "20aed0973b23aa05e69a1f5ead4561d3");
            $jssdk = new \JSSDK("wx9d72c537234b5159", "b70b96e27d3cc64ddf0f513bad4168f7");
            $signPackage = $jssdk->GetSignPackage();
            $this->assign("signPackage",$signPackage);
            if (! is_login() || (CONTROLLER_NAME == 'Login')) {
                $wxUserinfo = $jssdk->getWxUserinfo();
                if (empty($wxUserinfo->unionid)) {
                    $this->error("获取微信信息失败，重新获取",U('Login/index'));
                }
                $this->assign('unionid',$wxUserinfo->unionid);
                $this->assign('nickname',$wxUserinfo->nickname);
                $this->assign('headimgurl',$wxUserinfo->headimgurl);
                $user_id = D('Member')->where(array('openid'=>$wxUserinfo->unionid,'login_type'=>'wx'))->getField('uid');
                // 判断用户是否已注册
                if (intval($user_id) > 0) {
                    $login_result = D('Member')->login($user_id);
                    if ($login_result && !defined("UID")) {
                        define("UID", $user_id);
                    }
                }
            }else{
                $wx_openid = D('Member')->where(array('uid'=>UID))->getField("openid");
                if (empty($wx_openid)) {
                    $wxUserinfo = $jssdk->getWxUserinfo();
                    if (empty($wxUserinfo->unionid)) {
                        $this->error("获取微信信息失败，重新获取",U('Login/index'));
                    }
                    D('Member')->where(array('uid'=>UID))->save(array('login_type'=>'wx','openid'=>$wxUserinfo->unionid));
                    M('users','cmf_')->where(array('id'=>UID))->save(array('login_type'=>'wx','openid'=>$wxUserinfo->unionid));
                }
            }
        }else{
            $this->assign("is_wechat",0);
        }
    }

	/* 用户登录检测 */
	protected function login(){
		/* 用户登录检测 */
		is_login() || $this->error('您还没有登录，请先登录！', U('User/login'));
	}
	
	protected function referer($url, $referer = array()){
	    $referer && session('RETURN_REDIRECT', $referer);
	    $this->redirect($url);
	}
	
    protected function lists ($model,$where=array(),$order='',$base = array('status'=>array('egt',0)),$field=true){
        $options    =   array();
        $REQUEST    =   (array)I('request.');
        if(is_string($model)){
            $model  =   M($model);
        }

        $OPT        =   new \ReflectionProperty($model,'options');
        $OPT->setAccessible(true);

        $pk         =   $model->getPk();
        if($order===null){
            //order置空
        }else if ( isset($REQUEST['_order']) && isset($REQUEST['_field']) && in_array(strtolower($REQUEST['_order']),array('desc','asc')) ) {
            $options['order'] = '`'.$REQUEST['_field'].'` '.$REQUEST['_order'];
        }elseif( $order==='' && empty($options['order']) && !empty($pk) ){
            $options['order'] = $pk.' desc';
        }elseif($order){
            $options['order'] = $order;
        }
        unset($REQUEST['_order'],$REQUEST['_field']);

        $options['where'] = array_filter(array_merge( (array)$base, /*$REQUEST,*/ (array)$where ),function($val){
            if($val===''||$val===null){
                return false;
            }else{
                return true;
            }
        });
        if( empty($options['where'])){
            unset($options['where']);
        }
        $options      =   array_merge( (array)$OPT->getValue($model), $options );
        $total        =   $model->where($options['where'])->count();

        if( isset($REQUEST['r']) ){
            $listRows = (int)$REQUEST['r'];
        }else{
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }
        $page = new \Think\Page($total, $listRows, $REQUEST);
        if($total>$listRows){
            $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% ');
        }
        $p =$page->show();
        $this->assign('_page', $p? $p: '');
        $this->assign('_total',$total);
        $options['limit'] = $page->firstRow.','.$page->listRows;

        $model->setProperty('options',$options);

        return $model->field($field)->select();
    }

}
